package com.snow.platform.auth.controller;

import com.snow.framework.core.base.Result;
import com.snow.platform.auth.po.Menu;
import com.snow.platform.auth.service.api.MenuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    @RequestMapping(value = "/getMenuTree", method = RequestMethod.POST)
    @ResponseBody
    public Result getMenuTree(){
        Result result = null;
        List<Menu> menuList = menuService.selectList(null);

        List<Menu> menuRootList = new ArrayList<>();
        menuList.stream()
                .filter(menu -> {
                    if(null == menu.getParentId() || menu.getParentId().equals(0L)){
                        return true;
                    }
                    return false;
                })
                .forEach(menu -> {
                    menuRootList.add(menu);
                });

        if(menuRootList.size() > 0){
            menuRootList.stream()
                    .forEach(menu -> {
                        getChild(menu, menuList);
                    });
        }

        result = Result.ok().put("result", menuRootList);
        return result;
    }

    /**
     * @auth 李朋
     * @desc 递归遍历菜单
     * date 2018年3月14日15:10:12
     * @param parentMenu 上级菜单
     * @param menuList 当前登录人全部菜单集合
     */
    private static void getChild(Menu parentMenu, List<Menu> menuList){
        // 子菜单
        List<Menu> childMenuList = new ArrayList<>();
        for (Menu menu : menuList) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (null != menu.getParentId() && !menu.getParentId().equals(0L)) {
                if (menu.getParentId().equals(parentMenu.getId())) {
                    if(StringUtils.isBlank(menu.getUrl())){
                        getChild(menu, menuList);
                    }
                    childMenuList.add(menu);
                }
            }
        }
        if(childMenuList.size() > 0){
            parentMenu.setChildMenuList(childMenuList);
        }
    }

}
